package 算法.leetcode.str;

import org.junit.Test;

/**
 * @author lchenglong
 * @date 2020/12/4
 */
public class CountAndSay {
    @Test
    public void test() {
        System.out.println(countAndSay(5));
    }

    public String countAndSay(int n) {
        String str = null;
        if (n == 1) {
            return String.valueOf(1);
        }
       for (int i=2;i<=n;i++) {
           if (str == null) {
               str = countSay(String.valueOf(i-1));
           } else {
               str = countSay(str);
           }
       }
       return null;
    }

    public String countSay(String str) {
        StringBuilder stringBuilder = new StringBuilder();
        int count = 0;
        Character c = null;
        for (int i=0,size=str.length();i<size;i++) {
            if (c == null) {
                c = str.charAt(i);
                count++;
            } else {
                if (c.equals(str.charAt(i))) {
                    count ++;
                } else {
                    stringBuilder.append(count).append(c);
                    c = str.charAt(i);
                    count=1;
                }
            }

        }
        if (c!=null) {
            stringBuilder.append(count > 0?count:1).append(c);
        }
        return stringBuilder.toString();
    }
}
